import { createStore } from 'vuex'
import { getUserInfo, login, logout, getUserMenus } from '~/api/manager'
import { errorMsg } from '~/composables/utils'
import { setCache, removeCache } from '~/composables/localStorage'
import { constant, parseMenus } from '~/utils/globalv'
import SysRoleModule from './modules/sysRole.js'
import SystemModule from './modules/system'
import StyleModule from './modules/style'
import AssBusiTodoModule from './modules/assBusiTodo'

const store = createStore({
  state(){
    return {
      count: 0,
      token: '',
      user: {},
      asideMenu: {width: '250px', isExpand: true, tip: '折叠'},// 左侧导航栏默认展开状态，则显示为折叠图标并提示“折叠”
      menus: [],
      ruleNames: [],
      tableHeaderFontColor: '#5faaff', // 表格列头文字的颜色
      businessViewHeight: (window.innerHeight || document.body.clientHeight) - 64 - 44 -40, // 业务视图区域高度
      formLabelWidth4: '70px',
      fontWeight: 2000, // normal, bold
      filterFontColor: '#5faaff', // 有过滤条件的列头文字颜色
    }
  },
  mutations: {
    increment(state){
      state.count++
    },
    setUserInfo(state, user){
      state.user = user
    },
    setToken(state, token){
      state.token = token
    },
    setAsideWidth(state){
      state.asideMenu.isExpand = !state.asideMenu.isExpand
      // 处于展开状态则提示“折叠”，相反则提示“展开”
      state.asideMenu.tip = state.asideMenu.isExpand ? '折叠' : '展开'
      state.asideMenu.width = state.asideMenu.isExpand ? '250px' : '64px'// 折叠时宽度64，展开时250
    },
    setMenus(state, menus){
      state.menus = menus
    },
    setRuleNames(state, ruleNames){
      state.ruleNames = ruleNames
    }
  },
  actions: {
    login({commit},{username,password}){
      return new Promise((resolve,reject)=>{
        login(username,password).then(res => {
          if(res.code !== 1) reject(res)
          const token = 'chanchaw';
          // 同时写入两处数据：localStorage、vuex
          commit('setToken', token)
          commit('setUserInfo', res.data)

          setCache('token', 'chanchaw')
          setCache('userInfo', res.data)

          // 登录成功后立即获取当前用户的菜单权限
          getUserMenus().then(res => {
            const projMenus = parseMenus(res.data)
            commit('setMenus', projMenus)
            setCache(constant.menus, projMenus)
          })

          // 保存角色 - 不请求后端直接 MOCK 数据
          const rules = ['职员','经理']
          commit('setRuleNames',rules)
          setCache(constant.ruleNames, rules)

          resolve(res)
        }).catch(err => reject(err))
      })
      
    },
    logout({commit}){
      return new Promise((resolve, reject)=>{
        logout().then(res => {
          // 清除所有缓存数据
          removeCache('token')
          removeCache('userInfo')

          commit('setToken','')
          commit('setUserInfo',{})

          resolve(res)
        }).catch(err => reject(err))
      })
    },
    getUserInfo({commit}, userId){
      return new Promise((resolve, reject)=>{
        getUserInfo(userId).then(res => {
          if(res.code !== 1){
            errorMsg(res.msg);
            return
          }
          commit('setUserInfo', res.data)
          resolve(res.data)
        }).catch(err => reject(err))
      })
    },
  },
  modules: { sysRole: SysRoleModule, system: SystemModule, style: StyleModule,assBusiTodo: AssBusiTodoModule }
})

export default store
